import { getCurrentWindow } from '@tauri-apps/api/window'
import { listen } from '@tauri-apps/api/event'
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useState } from 'react'
import useCountdown from './useCountdown'

const win = getCurrentWindow()

function listener(name, cb) {
  return listen(name, event => {
    console.log("🚀 ~ file: useClock.jsx:11 ~ name, event:", name, event)
    cb(event.payload)
  })
}

async function setWinSize(x, y) {
  await invoke('set_win_size', { data: { width: x, height: y } })
}

function useClock(ref) {
  let clockTimer = null

  const [fontSize, setFontSize] = useState('36px')
  const [fontColor, setFontColor] = useState('#FF4A58')
  const [fontStyle, setFontStyle] = useState('Helvetica')
  const [showTime, setShowTime] = useState(new Date().toLocaleTimeString())

  const { isCountdownRunning, stopCountdownTimer, startCountdownTimer, formatTime } = useCountdown()

  async function handleMouseDown() {
    await win.startDragging()
  }

  function startClockTimer() {
    clockTimer && clockTimer() // 停止之前的计时器
    stopCountdownTimer() // 停止倒计时计时器

    const intervalId = setInterval(() => {
      setShowTime(new Date().toLocaleTimeString())
    }, 1000)
    return () => clearInterval(intervalId)
  }

  useEffect(() => {
    // 开启计时器
    clockTimer = startClockTimer()

    const unlistenFontSize = listener('change-font-size', setFontSize)
    const unlistenFontColor = listener('change-font-color', setFontColor)
    const unlistenFontStyle = listener('change-font-family', setFontStyle)
    const unlistenCountdown = listener('change-countdown', handleCountdown)

    // 取消监听
    return () => {
      unlistenFontSize.then(fn => fn())
      unlistenFontColor.then(fn => fn())
      unlistenFontStyle.then(fn => fn())
      unlistenCountdown.then(fn => fn())
    }
  }, [])

  useEffect(() => {
    const offsetWidth = ref.current.offsetWidth + 16
    const offsetHeight = ref.current.offsetHeight + 16

    // 发送消息给主进程, 通知窗口大小变化
    setWinSize(offsetWidth, offsetHeight)
  }, [fontSize, fontStyle])

  function handleCountdown(seconds) {
    if (seconds === 0 && !isCountdownRunning()) return

    if (seconds === 0 && isCountdownRunning()) {
      stopCountdownTimer() // 停止倒计时计时器
      clockTimer = startClockTimer() // 重新开始时间计时器
      return
    }

    setShowTime(formatTime(seconds * 1e3))
    clockTimer && clockTimer() // 停止时间计时器

    startCountdownTimer(seconds, value => {
      setShowTime(value)
    })
  }

  return {
    fontSize,
    fontColor,
    fontStyle,
    showTime,
    setShowTime,
    handleMouseDown,
  }
}
export default useClock
